package com.ruoyi.project.mobile.upload;

import java.io.File;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.utils.R;
import com.ruoyi.common.utils.RFactory;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.qiniu.QiNiuUploadUtil;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.AppBeanInjector;
import com.ruoyi.project.system.file.domain.UploadFile;
import com.ruoyi.project.system.file.service.IUploadFileService;

/**
 * 功能：
 *
 * @author：dell
 * @create：2020/6/29 9:05
 * @version：2020 Version：1.0
 * @company：老屋新房 Created with IntelliJ IDEA
 */
@RestController
@RequestMapping("/api/upload")
public class ApiUploadController {

	@Autowired
	private ServerConfig serverConfig;
	@Autowired
	private IUploadFileService uploadFileService;
	/**
	 * 通用上传请求
	 */
	@PostMapping
	@ResponseBody
	public R uploadFile(MultipartFile file) throws Exception
	{
		try
		{
			// 上传文件路径
			String filePath = RuoYiConfig.getUploadPath();
			StringBuffer fileRealName = new StringBuffer();
			String fileName = FileUploadUtils.extractFilename(file);
			// 上传并返回新文件名称
//			String fileName = FileUploadUtils.upload(filePath, file,fileRealName);
			AppBeanInjector.qiniuUploadUtil.upload(file.getBytes(),fileName);
//			String realPath = filePath+ File.separator+fileRealName;
			String url = QiNiuUploadUtil.getBaseUrl() + fileName;
			AjaxResult ajax = AjaxResult.success();
			ajax.put("fileName", fileName);
			ajax.put("url", url);
			ajax.put("realPath",url);

			//文件上传成功以后生成upload_file数据
//			this.uploadFileService.insertUploadFile(new UploadFile(null,url,realPath,null));


			return RFactory.generateR(ajax);
		}
		catch (Exception e)
		{
			return R.error(e.getMessage());
		}
	}

}
